package cn.yqn.basic.utils;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;
import java.util.Set;

/**
* @Description: 邮件发送工具类
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/7/26 15:39
*/
public class EmailUtils {
    private static JavaMailSender javaMailSender = ApplicationContextGetBeanHelper.getBean(JavaMailSender.class);

    /**
    * @Title: sendMailEasy
    * @Description: 简单邮件
    * @Author: Mr.She
    * @Version: 1.0
    * @Date:  2022/7/26 15:39
    * @Parameters:
    * @Return
    */
    public static void sendMailEasy(String subject,String text,String emailSetTo){
        // 1.准备发送的相关信息
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 1.1.设置发送人
        simpleMailMessage.setFrom("1120707667@qq.com");
        // 1.2.设置接收人
        simpleMailMessage.setTo(emailSetTo);
        // 1.3.设置邮件主题
        simpleMailMessage.setSubject(subject);
        // 1.4.设置邮件文本内容
        simpleMailMessage.setText(text);
        // 使用邮件核心对象发送邮件
        javaMailSender.send(simpleMailMessage);
    }

    /**
     * 复杂邮件
     * @param subject
     * @param text
     * @param emailSetTo
     * @param filePaths
     * @param isHtml
     */
    public static void sendMail(String subject, String text, String emailSetTo, Map<String,String> filePaths, boolean isHtml) {
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            // 设置发送人
            helper.setFrom("1120707667@qq.com");
            helper.setSubject(subject);
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText(text,isHtml);
            // 4.添加附件
            if (filePaths != null) {
                Set<String> keySet = filePaths.keySet();
                for (String s : keySet) {
                    helper.addAttachment(s,new File(filePaths.get(s)));
                }
            }
            // 5.设置收件人
            helper.setTo("1520931171@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}